<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增区段信息</el-button>
        <!--        <el-button type="primary" @click="handleAddModel">添加模型</el-button>-->
        <!--        <el-button type="primary" @click="handleAddModel">删除模型</el-button>-->
        <el-button type="primary" plain @click="toDetail(scope)">跳转区段详情页面</el-button>
        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope)">
          批量删除区段型号
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <DeviceDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="ts" name="monitoringProjectDetail">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import {Device, Model, MonitioringProject} from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import ModelDrawer from "@/views/proTable/components/ModelDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh } from "@element-plus/icons-vue";
import { getDModelList, addModel, updateModel, deleteModel } from "@/api/modules/new2";
import {
  deleteBatchDevice,
  deleteDevice,
  deleteMonitoringProjectList, getDeviceAllList,
  getDeviceList,
  getMonitoringProjectList, saveorupdateDeviceList,
  saveorupdateMonitoringProjectList
} from "@/api/modules/new";

import { useRoute } from "vue-router";
import {onMounted} from "vue";
import DeviceDrawer from "@/views/monitoringProject/components/DeviceDrawer.vue";
const route = useRoute();
const router = useRouter();

onMounted(() => {
  console.log(route.params)
  console.log(route.query)
});

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });


// 跳转详情页
const toDetail = (scope) => {
  console.log(scope.selectedList.length)
  if (scope.selectedList.length==1){
    const did=scope.selectedList[0].did
    router.push({ path: `/monitoringProject/deviceinformation`, query: { 'did': did }});
  }else{
    ElNotification({
      title: "温馨提示",
      message: "请选择一条数据",
      type: "warning"
    });
  }


};

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  console.log(data)
  return {
    list: data.records,
    total: data.total,
    pageNum: data.current,
    pageSize: data.size
  };
};
// 更新表单

// 获取后端数据，渲染到表格中
// 初始化数据
const getTableList =async (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  newParams.mid=route.query.mid
  console.log(newParams)
  const res = await getDeviceAllList(newParams);
  return { data: res }


};
// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();



// 表格配置项
const columns = reactive<ColumnProps<Device.ResDeviceList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { type: "sort", label: "Sort", width: 80 },
  { type: "expand", label: "Expand", width: 85 },
  {
    prop: "did",
    label: "监测设备id",
  },
  {
    prop: "name",
    label: "监测设备名",
    search: { el: "input", tooltip: "我是搜索提示" },

  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof DeviceDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Device.ResDeviceList> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? saveorupdateDeviceList : title === "编辑" ? saveorupdateDeviceList : undefined,
    getTableList: proTable.value?.getTableList,
    mid:route.query.mid,
    did:route.query.did
  };
  console.log('=====')
  console.log(params)
  drawerRef.value?.acceptParams(params);
};

// 删除用户信息
const deleteAccount = async (params: Device.ResDeviceList) => {
  await useHandleData(deleteDevice, { did: [params.did] }, `删除【${params.name}】型号`);
  proTable.value?.getTableList();
};

// 批量删除模型信息
const batchDelete = async (scope: any) => {
  const did = scope.selectedListIds
  await useHandleData(deleteBatchDevice, did, "删除所选模型信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};
</script>

